<!--
 这是来料检验单对话框组件，包含基本信息、供应商与物料、检测数据等多个标签页。
 支持新增和编辑来料检验单，使用了通用选择器组件和质检方案选择器组件。-->
<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="90%"
    append-to-body
    @close="handleClose"
    :fullscreen="false"
    class="iqc-dialog"
    :class="{'init-form-status': !showValidationErrors, 'show-validation': showValidationErrors}"
  >
    <el-alert
      v-if="formErrorCount > 0 && showValidationErrors"
      title="表单中有未填写的必填项"
      type="warning"
      :description="`共有 ${formErrorCount} 个必填项未完成，请填写完整后提交`"
      show-icon
      :closable="false"
      style="margin-bottom: 15px;"
    ></el-alert>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本信息" name="basic">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form ref="form" :model="form" :rules="showValidationErrors ? rules : {}" label-width="100px" size="small">
              <el-form-item label="检验单编号" prop="iqcCode" required>
                <el-input v-model="form.iqcCode" placeholder="请输入来料检验单编号" :disabled="form.iqcId !== null && form.iqcId !== undefined" :class="{'disabled-input': form.iqcId !== null && form.iqcId !== undefined}">
                  <el-button 
                    v-if="form.iqcId === null || form.iqcId === undefined" 
                    slot="append" 
                    icon="el-icon-refresh" 
                    @click="generateAutoCode" 
                    :loading="codeLoading">生成</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="检验单名称" prop="iqcName" required>
                <el-input v-model="form.iqcName" placeholder="请输入内容" />
              </el-form-item>
              <el-form-item label="质检方案" prop="templateId" required v-if="form.iqcId">
                <div class="code-input-wrapper">
                  <el-input v-model="form.templateId" placeholder="请选择质检方案" readonly />
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="small"
                    class="select-plan-btn"
                    @click="openInspectPlanDialog">选择</el-button>
                </div>
                <input type="hidden" v-model="form.templateCode" />
                <input type="hidden" v-model="form.templateName" />
              </el-form-item>
              <el-form-item label="单据状态" prop="status" required>
                <el-select v-model="form.status" placeholder="请选择单据状态" style="width: 100%" disabled>
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="form2" :model="form" :rules="showValidationErrors ? rules : {}" label-width="100px" size="small">
              <el-form-item label="来源单据" prop="sourceDocId" required>
                <el-input v-model="form.sourceDocCode" placeholder="请选择来源单据" readonly>
                  <el-button slot="append" icon="el-icon-search" @click="openSourceDocSelector"></el-button>
                </el-input>
                <input type="hidden" v-model="form.sourceDocId" />
              </el-form-item>
              <el-form-item label="来源单据类型" prop="sourceDocType" required>
                <el-select v-model="form.sourceDocType" placeholder="请选择来源单据类型" style="width: 100%">
                  <el-option v-for="item in sourceDocTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="来源单据编号" prop="sourceDocCode" required>
                <el-input v-model="form.sourceDocCode" placeholder="请输入来源单据编号" readonly />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="form3" :model="form" :rules="showValidationErrors ? rules : {}" label-width="100px" size="small">
              <el-form-item label="来料日期" prop="reciveDate" required>
                <el-date-picker clearable
                  v-model="form.reciveDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择来料日期"
                  style="width: 100%"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="检测日期" prop="inspectDate" required>
                <el-date-picker clearable
                  v-model="form.inspectDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择检测日期"
                  style="width: 100%"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="检测人员" prop="inspectorId" required class="form-item">
                <div class="code-input-wrapper">
                  <el-input
                    v-model="form.inspectorName"
                    placeholder="请选择检测人员"
                    readonly
                    style="width: 100%"
                  />
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="small"
                    class="select-btn"
                    @click="openSelectUserDialog">
                    选择
                  </el-button>
                </div>
                <!-- inspectorId字段现在存储用户名称，与inspectorName相同 -->
                <input type="hidden" v-model="form.inspectorId" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="供应商与物料" name="supplierAndMaterial">
        <el-row :gutter="20">
          <!-- 供应商信息部分 -->
          <el-col :span="12">
            <div class="section-title">供应商信息</div>
            <el-row :gutter="20">

              <el-col :span="12">
                <el-form ref="form5" :model="form" :rules="showValidationErrors ? rules : {}" label-width="100px" size="small">
                  <el-form-item label="供应商名称" prop="supplierName" required>
                    <el-input v-model="form.supplierName" placeholder="请输入供应商名称" readonly />
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-col>

          <!-- 物料信息部分 -->
          <el-col :span="12" v-if="form.iqcId">
            <div class="section-title">物料信息</div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form ref="form7" :model="form" :rules="showValidationErrors ? rules : {}" label-width="100px" size="small">
                  <el-form-item label="货物编码" prop="goodsCode" required>
                    <el-input v-model="form.goodsCode" placeholder="请选择货物编码" readonly />
                  </el-form-item>
                  <el-form-item label="货物名称" prop="goodsName" required>
                    <el-input v-model="form.goodsName" placeholder="请输入货物名称" readonly />
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="12">
                <el-form ref="form8" :model="form" :rules="showValidationErrors ? rules : {}" label-width="100px" size="small">
                  <el-form-item label="规格型号" prop="stockSfn" required>
                    <el-input v-model="form.stockSfn" placeholder="请输入规格型号" readonly />
                  </el-form-item>
                  <el-form-item label="单位" prop="unitName" required>
                    <el-input v-model="form.unitName" placeholder="请输入单位" readonly />
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 检测数据卡片 - 仅在编辑模式下显示 -->
      <el-tab-pane label="检测数据" name="inspection" v-if="form.iqcId">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form ref="form10" :model="form" :rules="showValidationErrors ? rules : {}" label-width="120px" size="small">
              <el-form-item label="最低检测数" prop="quantityMinCheckNum">
                <el-input-number
                  v-model="form.quantityMinCheckNum"
                  placeholder="请输入最低检测数"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  :disabled="true"
                />
                <div class="form-tip" v-if="form.quantityMinCheckNum">
                  <i class="el-icon-info"></i> 规定最低检测数: {{ form.quantityMinCheckNum }}
                </div>
              </el-form-item>
              <el-form-item label="最大不合格数" prop="quantityMaxUnqualifiedNum">
                <el-input-number
                  v-model="form.quantityMaxUnqualifiedNum"
                  placeholder="请输入最大不合格数"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  :disabled="true"
                />
                <div class="form-tip" v-if="form.quantityMaxUnqualifiedNum">
                  <i class="el-icon-info"></i> 规定最大不合格数: {{ form.quantityMaxUnqualifiedNum }}
                </div>
              </el-form-item>
              <el-form-item label="本次接收数量" prop="quantityRecivedNum" required>
                <el-input-number
                  v-model="form.quantityRecivedNum"
                  placeholder="请输入本次接收数量"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="handleRecivedNumChange"
                />
              </el-form-item>
              <el-form-item label="本次检测数量" prop="quantityCheckNum" required>
                <el-input-number
                  v-model="form.quantityCheckNum"
                  placeholder="请输入本次检测数量"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="handleQuantityChange"
                />
                <div class="form-tip warning" v-if="form.quantityMinCheckNum && form.quantityCheckNum < form.quantityMinCheckNum">
                  <i class="el-icon-warning"></i> 检测数量低于规定最低检测数
                </div>
                <div class="form-tip warning" v-if="form.quantityRecivedNum && form.quantityCheckNum > form.quantityRecivedNum">
                  <i class="el-icon-warning"></i> 检测数量不能超过接收数量
                </div>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="form11" :model="form" :rules="showValidationErrors ? rules : {}" label-width="120px" size="small">
              <el-form-item label="合格数" prop="quantityQualifiedNum" required>
                <el-input-number
                  v-model="form.quantityQualifiedNum"
                  placeholder="请输入合格数"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="updateUnqualifiedNum"
                />
              </el-form-item>
              <el-form-item label="不合格数" prop="quantityUnqualifiedNum" required>
                <el-input-number
                  v-model="form.quantityUnqualifiedNum"
                  placeholder="请输入不合格数"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="handleUnqualifiedNumChange"
                />
                <div class="form-tip warning" v-if="form.quantityMaxUnqualifiedNum && form.quantityUnqualifiedNum > form.quantityMaxUnqualifiedNum">
                  <i class="el-icon-warning"></i> 不合格数已超过规定最大值，检测结果已自动设为不合格
                </div>
              </el-form-item>
              <el-form-item label="检测结果" prop="checkResult" required>
                <el-select v-model="form.checkResult" placeholder="请选择检测结果" style="width: 100%">
                  <el-option v-for="item in checkResultOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="form12" :model="form" :rules="showValidationErrors ? rules : {}" label-width="120px" size="small">
              <el-form-item label="致命缺陷数量" prop="crQuantityNum">
                <el-input-number
                  v-model="form.crQuantityNum"
                  placeholder="请输入致命缺陷数量"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="calculateDefectRates"
                  :disabled="!form.quantityUnqualifiedNum"
                  :max="(form.quantityUnqualifiedNum || 0) - (form.majQuantityNum || 0) - (form.minQuantityNum || 0)"
                />
              </el-form-item>
              <el-form-item label="严重缺陷数量" prop="majQuantityNum">
                <el-input-number
                  v-model="form.majQuantityNum"
                  placeholder="请输入严重缺陷数量"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="calculateDefectRates"
                  :disabled="!form.quantityUnqualifiedNum"
                  :max="(form.quantityUnqualifiedNum || 0) - (form.crQuantityNum || 0) - (form.minQuantityNum || 0)"
                />
              </el-form-item>
              <el-form-item label="轻微缺陷数量" prop="minQuantityNum">
                <el-input-number
                  v-model="form.minQuantityNum"
                  placeholder="请输入轻微缺陷数量"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="calculateDefectRates"
                  :disabled="!form.quantityUnqualifiedNum"
                  :max="(form.quantityUnqualifiedNum || 0) - (form.crQuantityNum || 0) - (form.majQuantityNum || 0)"
                />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form ref="form13" :model="form" :rules="showValidationErrors ? rules : {}" label-width="120px" size="small">
              <el-form-item label="致命缺陷率" prop="crRate">
                <el-input-number
                  v-model="form.crRate"
                  placeholder="请输入致命缺陷率"
                  :min="0"
                  :max="100"
                  :precision="2"
                  :step="0.01"
                  style="width: 100%"
                  :disabled="true"
                />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="form14" :model="form" :rules="showValidationErrors ? rules : {}" label-width="120px" size="small">
              <el-form-item label="严重缺陷率" prop="majRate">
                <el-input-number
                  v-model="form.majRate"
                  placeholder="请输入严重缺陷率"
                  :min="0"
                  :max="100"
                  :precision="2"
                  :step="0.01"
                  style="width: 100%"
                  :disabled="true"
                />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-form ref="form15" :model="form" :rules="showValidationErrors ? rules : {}" label-width="120px" size="small">
              <el-form-item label="轻微缺陷率" prop="minRate">
                <el-input-number
                  v-model="form.minRate"
                  placeholder="请输入轻微缺陷率"
                  :min="0"
                  :max="100"
                  :precision="2"
                  :step="0.01"
                  style="width: 100%"
                  :disabled="true"
                />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 关联检查项列表标签页，仅在编辑模式下可见 -->
      <el-tab-pane v-if="form.iqcId" label="关联检查项" name="indexList">
        <related-index-list
          :iqcId="form.iqcId"
          :templateId="form.templateId"
          :isEdit="form.iqcId !== null && form.iqcId !== undefined"
        ></related-index-list>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 使用过程检验单相同的质检方案选择器组件 -->
    <inspect-plan-selector
      :visible.sync="inspectPlanDialogVisible"
      :allowedTypes="['4']"
      :qc-types="4"
      @select="handleInspectPlanSelect"
      @close="closeInspectPlanDialog"
    />

    <!-- 使用通用选择器组件 - 来源单据选择 -->
    <common-selector
      title="选择来源单据"
      :visible.sync="sourceDocSelectorVisible"
      :searchItems="sourceDocSearchItems"
      :columns="sourceDocColumns"
      :initQuery="sourceDocQueryParams"
      :fetchDataMethod="fetchSourceDocs"
      :showDebug="true"
      @select="handleSourceDocSelect"
      @cancel="sourceDocSelectorVisible = false"
    />

    <!-- 使用通用选择器组件 - 供应商选择 -->
    <common-selector
      title="选择供应商"
      :visible.sync="supplierSelectorVisible"
      :searchItems="supplierSearchItems"
      :columns="supplierColumns"
      :initQuery="supplierQueryParams"
      :dataOptions="supplierList"
      :showDebug="true"
      @select="handleSupplierSelect"
      @cancel="supplierSelectorVisible = false"
    />

    <!-- 使用通用选择器组件 - 物料选择 -->
    <common-selector
      title="选择货物"
      :visible.sync="materialSelectorVisible"
      :searchItems="materialSearchItems"
      :columns="materialColumns"
      :initQuery="materialQueryParams"
      :dataOptions="materialList"
      :showDebug="true"
      @select="handleMaterialSelect"
      @cancel="materialSelectorVisible = false"
    />

    <!-- 用户选择对话框 -->
    <select-user-dialog
      :visible.sync="selectUserDialogVisible"
      title="选择检测人员"
      :multi="false"
      @confirm="handleUserConfirm"
    />

  </el-dialog>
</template>

<script>
import { addIqc, updateIqc, getQcTemplateList, getQcTemplateProductList, checkIqcCodeUnique, selectCkProductRecptDetectSingle } from "@/api/qc/IncomingInspection";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers.js";

// 引入通用选择器组件
import CommonSelector from "./CommonSelector.vue";
// 引入关联检测项列表组件
import RelatedIndexList from "./RelatedIndexList.vue";
// 引入质检方案选择器组件
import InspectPlanSelector from "@/views/qc/ProcesInspection/components/InspectPlanSelector.vue";
// 引入用户选择对话框组件
import SelectUserDialog from "@/views/qc/components/SelectUserDialog.vue";
// 查询检测方案
import { selectQcTemplateProductMaterialCode,selectQcTemplateProductCode } from "@/api/qc/QualitySchemeOrder";

export default {
  name: "IqcDialog",
  components: {
    CommonSelector,
    RelatedIndexList,
    InspectPlanSelector,
    SelectUserDialog
  },
  props: {
    // 是否显示对话框
    visible: {
      type: Boolean,
      default: false
    },
    // 标题
    title: {
      type: String,
      default: ""
    },
    // 表单数据
    iqcData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 添加调试模式开关
      debugMode: true, // 设置为true开启详细日志
      templateQueryStatus: {
        attempted: false, // 是否尝试过查询
        success: false,   // 查询是否成功
        message: "",      // 状态消息
        lastCode: ""      // 最后查询的编码
      },

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },

      // 当前活动标签页
      activeTab: 'basic',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        iqcCode: [
          { required: true, message: "来料检验单编号不能为空", trigger: "blur" }
        ],
        iqcName: [
          { required: true, message: "检验单名称不能为空", trigger: "blur" }
        ],
        templateId: [
          { required: true, message: "质检方案不能为空", trigger: "change" }
        ],
        sourceDocType: [
          { required: true, message: "来源单据类型不能为空", trigger: "change" }
        ],
        sourceDocCode: [
          { required: true, message: "来源单据编号不能为空", trigger: "blur" }
        ],
        supplierId: [
          { required: true, message: "供应商ID不能为空", trigger: "blur" }
        ],
        supplierName: [
          { required: true, message: "供应商名称不能为空", trigger: "blur" }
        ],
        goodsCode: [
          { required: true, message: "货物编码不能为空", trigger: "blur" }
        ],
        goodsName: [
          { required: true, message: "货物名称不能为空", trigger: "blur" }
        ],
        stockSfn: [
          { required: true, message: "规格型号不能为空", trigger: "blur" }
        ],
        unitName: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        quantityRecivedNum: [
          { required: true, message: "本次接收数量不能为空", trigger: "blur" }
        ],
        quantityCheckNum: [
          { required: true, message: "本次检测数量不能为空", trigger: "blur" }
        ],
        quantityQualifiedNum: [
          { required: true, message: "合格数不能为空", trigger: "blur" }
        ],
        quantityUnqualifiedNum: [
          { required: true, message: "不合格数不能为空", trigger: "blur" }
        ],
        checkResult: [
          { required: true, message: "检测结果不能为空", trigger: "change" }
        ],
        inspectDate: [
          { required: true, message: "检测日期不能为空", trigger: "blur" }
        ],
        reciveDate: [
          { required: true, message: "来料日期不能为空", trigger: "blur" }
        ],
        inspectorId: [
          { required: true, message: "检测人员不能为空", trigger: ["blur", "change"] },
          { type: "string", message: "检测人员必须是字符串", trigger: ["blur", "change"] }
        ],
        status: [
          { required: true, message: "单据状态不能为空", trigger: "change" }
        ]
      },

      // 表单验证状态
      formErrorCount: 0,
      validateOnSubmit: false,
      // 控制是否显示验证错误信息
      showValidationErrors: false,

      // 字典数据
      statusOptions: [
        { value: 1, label: "草稿" },
        { value: 2, label: "已提交" },
        { value: 3, label: "已审核" }
      ],
      // 来源单据类型选项
      sourceDocTypeOptions: [
        { value: 2, label: "来料货检验单" }
      ],
      // 质检方案选择器
      inspectPlanDialogVisible: false,

      // 来源单据选择器
      sourceDocSelectorVisible: false,

      sourceDocQueryParams: {
        recpt_code: '',
        recpt_name: '',
        status: 1
      },
      sourceDocSearchItems: [
        { label: '单据编号', field: 'recpt_code', type: 'input' },
        { 
          label: '单据名称',
          field: 'recpt_name',
          type: 'input'
        }
      ],
      sourceDocColumns: [
        { prop: 'recpt_code', label: '单据编号' },
        { prop: 'recpt_name', label: '单据名称' },
        { prop: 'supplier_name', label: '供应商名称' },
        {
          prop: 'recpt_date',
          label: '来料日期',
          formatter: (row) => row.recpt_date ? new Date(row.recpt_date).toLocaleDateString() : ''
        },
        { prop: 'batch_code', label: '批次号' }
      ],

      // 供应商选择器
      supplierSelectorVisible: false,
      supplierList: [],
      supplierQueryParams: {
        code: '',
        name: ''
      },
      supplierSearchItems: [
        { label: '供应商编码', field: 'code', type: 'input' },
        { label: '供应商名称', field: 'name', type: 'input' }
      ],
      supplierColumns: [
        { prop: 'supplierId', label: '供应商ID', width: '100' },
        { prop: 'supplierCode', label: '供应商编码' },
        { prop: 'supplierName', label: '供应商名称' },
        { prop: 'supplierNick', label: '供应商简称' },
        { prop: 'contactPerson', label: '联系人' },
        { prop: 'contactPhone', label: '联系电话' }
      ],

      // 物料选择器
      materialSelectorVisible: false,
      materialList: [],
      materialQueryParams: {
        goods_code: '',
        goods_name: ''
      },
      materialSearchItems: [
        { label: '货物编码', field: 'goods_code', type: 'input' },
        { label: '货物名称', field: 'goods_name', type: 'input' }
      ],
      materialColumns: [
        { prop: 'goods_code', label: '货物编码', width: '120' },
        { prop: 'goods_name', label: '货物名称' },
        { prop: 'stock_sfn', label: '规格型号' },
        { prop: 'unit_name', label: '单位', width: '80' },
        { prop: 'cr_rate', label: '致命缺陷率', width: '100' },
        { prop: 'maj_rate', label: '严重缺陷率', width: '100' },
        { prop: 'min_rate', label: '轻微缺陷率', width: '100' }
      ],

      // 检测项列表相关数据
      indexListLoading: false,

      // 用户选择对话框
      selectUserDialogVisible: false,
      // 标记是否已设置表单监听
      formWatcherSetup: false,

      // 初始化标记，用于判断是否为初次渲染
      isInitialRender: true,

      // 自动生成编码相关数据
      codeLoading: false,
      isSystemCode: true // 是否使用系统编号
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      }
    },
    // 根据是否有ID判断是新增还是修改，显示对应的标题
    dialogTitle() {
      return this.form.iqcId ? "修改来料检验单" : "新增来料检验单";
    },
    // 动态生成检测结果选项
    checkResultOptions() {
      const options = [
        { value: 1, label: "合格" },
        { value: 2, label: "不合格" },
        { value: 3, label: "待检" }
      ];
      // 如果是编辑模式，禁用"待检"选项
      if (this.form.iqcId) {
        const pendingOption = options.find(opt => opt.value === 3);
        if (pendingOption) {
          pendingOption.disabled = true;
        }
      }
      return options;
    },
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        // 对话框打开时初始化
        this.handleDialogOpen();
      } else {
        // 对话框关闭时重置
        this.showValidationErrors = false;
      }
    },
    dialogVisible(val) {
      // 当对话框显示状态改变时
      if (val) {
        // 对话框打开，确保不显示验证错误
        this.showValidationErrors = false;
        // 初始化后，延迟一下再进行一次检查，确保验证提示不会显示
        setTimeout(() => {
          this.clearAllValidation();
        }, 100);
        
        // 确保状态字段有默认值
        if (!this.form.iqcId) {
          this.form.status = 2; // 新增模式默认为已提交状态
        } else {
          this.form.status = 3; // 编辑模式默认为已审核状态
        }
      }
    },
    iqcData: {
      handler(val) {
        if (val) {
          this.logDebug('iqcData监听触发', val);
          
          // 深拷贝对象
          const formData = Object.assign({}, val);

          // 确保sourceDocType有默认值
          if (formData.sourceDocType === null || formData.sourceDocType === undefined) {
            formData.sourceDocType = 2; // 默认：来料货检验单
          }

          // 确保数值字段是数字类型
          ['sourceDocType', 'checkResult'].forEach(field => {
            if (formData[field] !== null && formData[field] !== undefined) {
              formData[field] = Number(formData[field]);
            }
          });

          // 设置状态字段 - 根据是否有ID判断设置不同的状态
          if (formData.iqcId) {
            // 编辑模式默认为已审核状态
            formData.status = 3;
          } else {
            // 新增模式默认为已提交状态
            formData.status = 2;
          }

          // 处理检测人员字段显示问题
          this.logDebug('编辑模式 - 处理前的检测人员数据:', {
            inspectorId: formData.inspectorId,
            inspectorName: formData.inspectorName
          });

          // 如果inspectorId存在但inspectorName不存在，则将inspectorId的值复制给inspectorName
          if (formData.inspectorId && !formData.inspectorName) {
            formData.inspectorName = formData.inspectorId;
            this.logDebug('已将inspectorId的值复制给inspectorName:', formData.inspectorName);
          }
          
          // 如果我们现在使用名称作为inspectorId字段的值，确保类型正确
          if (formData.inspectorId) {
            formData.inspectorId = String(formData.inspectorId);
          }

          this.logDebug('编辑模式 - 处理后的检测人员数据:', {
            inspectorId: formData.inspectorId,
            inspectorName: formData.inspectorName
          });

          this.form = formData;

          // 重置模板查询状态
          this.resetTemplateQueryStatus();
          
          // 表单数据初始化后，设置监听，但不显示验证错误
          this.$nextTick(() => {
            this.setupFormWatchers();
            // 延迟后清除可能出现的错误状态
            setTimeout(() => {
              this.clearAllValidation();
            }, 50);
          });
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    // 加载模拟数据
    this.loadMockData();
    // 确保初始状态不显示验证错误
    this.showValidationErrors = false;
    this.isInitialRender = true;
    this.logDebug('组件created生命周期');
  },
  mounted() {
    // 确保初始化时不显示验证错误
    this.showValidationErrors = false;
    // 添加一个延时清除所有验证提示
    setTimeout(() => {
      this.clearAllValidation();
    }, 100);
    this.logDebug('组件mounted生命周期');
    
    // 在mounted时检查是否需要自动查询检测方案
    this.$nextTick(() => {
      // if (this.form.goodsCode && !this.templateQueryStatus.attempted) {
      //   this.logDebug("mounted时检测到货物编码，准备自动查询检测方案:", this.form.goodsCode);
      //   this.findTemplateByCode(this.form.goodsCode);
      // }
    });
  },
  methods: {
    // 调试日志方法
    logDebug(message, data) {
      if (this.debugMode) {
        const timestamp = new Date().toLocaleTimeString();
        const prefix = `[IQC调试 ${timestamp}] `;
        if (data !== undefined) {
          console.log(prefix + message, data);
        } else {
          console.log(prefix + message);
        }
      }
    },
    
    // 重置模板查询状态
    resetTemplateQueryStatus() {
      this.templateQueryStatus = {
        attempted: false,
        success: false,
        message: "",
        lastCode: ""
      };
    },

    selectCkProductRecptDetectSingle,

    /** 提交按钮 */
    submitForm() {
      this.isInitialRender = false;
      this.showValidationErrors = true; // 立即显示验证错误

      // 强制应用验证规则
      this.$nextTick(() => {
        // 使用Promise收集所有表单验证结果
        const formRefs = ["form", "form2", "form3", "form5", "form7", "form8", "form10", "form11", "form12", "form13", "form14", "form15"];
        const validatePromises = [];

        formRefs.forEach(formName => {
          if (this.$refs[formName]) {
            validatePromises.push(
              new Promise(resolve => {
                this.$refs[formName].validate(valid => {
                  resolve(valid);
                });
              })
            );
          }
        });

        // 等待所有验证完成
        Promise.all(validatePromises).then(results => {
          // 检查是否所有表单都验证通过
          const allValid = results.every(valid => valid);

          if (allValid) {
            // 所有验证通过，执行提交
            this.checkUniqueThenSubmit();
          } else {
            // 验证未通过，计算错误数量
            this.validateAllForms(true);
            this.$message.error('表单有必填项未完成，请填写完整后提交');

            // 跳转到第一个有错误的表单
            this.jumpToFirstErrorTab();
          }
        });
      });
    },

    // 跳转到第一个有错误的表单标签页
    jumpToFirstErrorTab() {
      // 检查基本信息标签页
      const basicFormRefs = ["form", "form2", "form3"];
      for (const formName of basicFormRefs) {
        if (this.hasFormError(formName)) {
          this.activeTab = "basic";
          return;
        }
      }

      // 检查供应商与物料标签页
      const supplierFormRefs = ["form5", "form7", "form8"];
      for (const formName of supplierFormRefs) {
        if (this.hasFormError(formName)) {
          this.activeTab = "supplierAndMaterial";
          return;
        }
      }

      // 默认跳转到检测数据标签页
      this.activeTab = "inspection";
    },

    // 检查表单是否有错误
    hasFormError(formName) {
      if (!this.$refs[formName]) return false;

      let hasError = false;
      this.$refs[formName].validate(valid => {
        hasError = !valid;
      });
      return hasError;
    },

    // 检查唯一性然后提交
    checkUniqueThenSubmit() {
      // 检查是否存在重复的检验单据
      if (!this.form.iqcId && this.form.sourceDocId && this.form.goodsCode) {
        checkIqcCodeUnique(this.form.sourceDocId, this.form.goodsCode).then(res => {
          if (!res) {
            this.$message.error('已存在相同来源单据和货物编码的检验单');
            return;
          } else {
            this.doSubmit();
          }
        }).catch(error => {
          console.error('检查唯一性失败', error);
          this.$message.warning('检查唯一性失败，请检查网络连接');
        });
      } else {
        this.doSubmit();
      }
    },

    // 执行实际的提交操作
    async doSubmit() {      
      // 如果检测结果为"待检"，弹出确认框
      if (this.form.checkResult == 3) {
        this.$confirm('检测结果为"待检"，是否确认提交?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.performSubmit();
        }).catch(() => {
          this.$message.info('已取消提交');
        });
      } else {
        this.performSubmit();
      }
    },
    
    async performSubmit() {
       // 最后检查必填字段
      if (!this.form.iqcCode) {
        this.$message.error('检验单编号不能为空');
        this.activeTab = 'basic';
        return;
      }

      if (!this.form.iqcName) {
        this.$message.error('检验单名称不能为空');
        this.activeTab = 'basic';
        return;
      }

      if (!this.form.sourceDocCode) {
        this.$message.error('来源单据编号不能为空');
        this.activeTab = 'basic';
        return;
      }

      if (!this.form.status) {
        this.$message.error('单据状态不能为空');
        this.activeTab = 'basic';
        return;
      }

      // 如果是新增且开启系统编号，获取真正的消费编号
      if (!this.form.iqcId && this.isSystemCode) {
        try {
          // 使用getAutoNumbersConsume消费流水号
          const response = await getAutoNumbersConsume(9);
          if (response && response.code === 200) {
            this.form.iqcCode = response.msg;
          } else {
            this.$message.error('获取最终编号失败，请重试');
            return;
          }
        } catch (error) {
          this.$message.error('获取最终编号失败，请重试');
          return;
        }
      }

      // 确保inspectorId是字符串类型
      if (this.form.inspectorId) {
        this.form.inspectorId = String(this.form.inspectorId);
      }

      // 创建一个新对象，处理字段映射问题
      const submitData = { ...this.form };
      
      // 确保类型正确
      if (submitData.sourceDocType !== undefined && submitData.sourceDocType !== null) {
        submitData.sourceDocType = String(submitData.sourceDocType);
      }
      
      if (submitData.checkResult !== undefined && submitData.checkResult !== null) {
        submitData.checkResult = String(submitData.checkResult);
      }
      
      if (submitData.status !== undefined && submitData.status !== null) {
        submitData.status = String(submitData.status);
      }
      
      this.logDebug('提交数据处理后:', submitData);
      
      // 必填校验通过，执行API请求
      const apiAction = this.form.iqcId
        ? updateIqc(submitData)
        : addIqc(submitData);

      this.$modal.loading("正在提交数据，请稍候...");
      apiAction.then((response) => {
        this.$modal.closeLoading();
        this.$modal.msgSuccess(this.form.iqcId ? "修改成功" : "新增成功");

        // 关闭对话框并通知父组件操作成功
        this.$emit("success", {});
      }).catch(error => {
        this.$modal.closeLoading();
        // 显示更详细的错误信息
        this.logDebug('提交失败', error);
        const errorMessage = error.response && error.response.data && error.response.data.message
          ? error.response.data.message
          : '操作失败';
        this.$modal.msgError(errorMessage);
      });
    },

    // ======== 加载数据 ========
    loadMockData() {
      // 模拟来源单据数据（暂时保留）
      this.sourceDocList = [
        { docId: 101, docType: 1, docCode: "SH202307001", createTime: "2023-07-01" },
        { docId: 102, docType: 2, docCode: "LR202307002", createTime: "2023-07-02" },
        { docId: 103, docType: 3, docCode: "PC202307003", createTime: "2023-07-03" }
      ];

      // 模拟供应商数据（暂时保留）
      this.supplierList = [
        { supplierId: 1001, supplierCode: "SUP001", supplierName: "北京科技有限公司", supplierNick: "北科", contactPerson: "张三", contactPhone: "13800138001" },
        { supplierId: 1002, supplierCode: "SUP002", supplierName: "上海工业集团", supplierNick: "上工", contactPerson: "李四", contactPhone: "13800138002" },
        { supplierId: 1003, supplierCode: "SUP003", supplierName: "广州材料有限公司", supplierNick: "广材", contactPerson: "王五", contactPhone: "13800138003" }
      ];

      // 模拟物料数据（暂时保留）
      this.materialList = [
        { goods_code: "M001", goods_name: "铝合金板", stock_sfn: "1000x2000x3mm", unit_name: "张" },
        { goods_code: "M002", goods_name: "钢管", stock_sfn: "Φ50x2mm", unit_name: "米" },
        { goods_code: "M003", goods_name: "电子元件", stock_sfn: "规格型号A", unit_name: "个" }
      ];
    },

    // ======== 来源单据选择器相关方法 ========
    openSourceDocSelector() {
      this.sourceDocSelectorVisible = true;
      // 确保在打开选择器时数据已经加载
      if (!this.sourceDocList || this.sourceDocList.length === 0) {
        this.loadMockData();
      }
      console.log("sourceDocList:", this.sourceDocList);
      
      // 重置查询参数以加载全部数据
      this.sourceDocQueryParams = {
        recpt_code: '',
        recpt_name: '',
        status: 1
      };
    },
    handleSourceDocSelect(row) {
      this.logDebug('选择来源单据', row);
      
      this.form.sourceDocId = row.recpt_id;
      this.form.sourceDocType = row.docType;
      this.form.sourceDocCode = row.recpt_code;
      this.form.supplierId = row.supplier_id;
      this.form.supplierCode = row.supplier_code;
      this.form.supplierName = row.supplier_name;
      this.form.batchCode = row.batch_code;
      this.form.reciveDate = row.recpt_date;

      // 回显货物信息
      if (row.goods_code) {
        this.logDebug('【选择来源单据】获取到的货物编码：', row.goods_code);
        this.form.goodsCode = row.goods_code;

        // 重置模板查询状态
        this.resetTemplateQueryStatus();
        
        // 根据货物编码自动查询检测方案
        this.$nextTick(() => {
          this.findTemplateByCode(row.goods_code);
        });
      } else {
        this.logDebug('【选择来源单据】未获取到货物编码，无法查询检测方案');
      }
      
      if (row.goods_name) {
        this.form.goodsName = row.goods_name;
      }
      if (row.stock_sfn) {
        this.form.stockSfn = row.stock_sfn;
      }
      if (row.unit_name) {
        this.form.unitName = String(row.unit_name);
      }

      this.logDebug("已回显货物信息:", {
        goodsCode: this.form.goodsCode,
        goodsName: this.form.goodsName,
        stockSfn: this.form.stockSfn,
        unitName: this.form.unitName
      });
    },

    // ======== 供应商选择器相关方法 ========
    openSupplierSelector() {
      this.supplierSelectorVisible = true;
      // 确保在打开选择器时数据已经加载
      if (!this.supplierList || this.supplierList.length === 0) {
        this.loadMockData();
      }
      console.log("supplierList:", this.supplierList);
    },
    handleSupplierSelect(row) {
      this.form.supplierId = row.supplierId;
      this.form.supplierCode = row.supplierCode;
      this.form.supplierName = row.supplierName;
      this.form.supplierNick = row.supplierNick;
      // 可添加其他需要的字段
    },

    // ======== 物料选择器相关方法 ========
    openMaterialSelector() {
      // 检查是否已选择质检方案
      if (!this.form.templateId) {
        this.$message.warning('请先选择质检方案，再选择货物');
        return;
      }

      // 显示物料选择器
      this.initMaterialList();
      this.materialSelectorVisible = true;
      console.log("materialList:", this.materialList);
    },
    handleMaterialSelect(row) {
      this.logDebug('选择物料', row);
      
      this.form.goodsCode = row.goods_code;
      this.form.goodsName = row.goods_name;
      this.form.stockSfn = row.stock_sfn;
      // 修改这里，确保unit_name正确转换为驼峰格式
      if (row.unit_name) {
        this.form.unitName = String(row.unit_name);
      }

      // 重置模板查询状态
      this.resetTemplateQueryStatus();
      
      // 根据货物编码自动查询检测方案
      this.$nextTick(() => {
        this.findTemplateByCode(row.goods_code);
      });
    },

    // 自动生成编码
    generateAutoCode() {
      if (!this.isSystemCode) {
        this.form.iqcCode = '';
        return;
      }
      
      this.codeLoading = true;
      getAutoNumbers(9).then(response => {
        if (response.code === 200) {
          this.form.iqcCode = response.msg;
          if (this.$refs.form) {
            this.$refs.form.validateField('iqcCode');
          }
          this.$message.success('编号预览生成成功');
        } else {
          this.$message.error('获取编号预览失败');
        }
      }).catch(() => {
        this.$message.error("生成编号预览异常");
      }).finally(() => {
        this.codeLoading = false;
      });
    },

    // 打开质检方案选择对话框
    openInspectPlanDialog() {
      // 检查是否已有检测方案ID
      if (this.form.templateId) {
        this.$confirm('当前已选择检测方案，是否重新选择?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户确认重新选择
          this.inspectPlanDialogVisible = true;
        }).catch(() => {
          // 用户取消重新选择
          this.$message.info('已取消重新选择');
        });
      } else {
        // 直接打开选择对话框
        this.inspectPlanDialogVisible = true;
      }
    },

    // 关闭质检方案选择对话框
    closeInspectPlanDialog() {
      this.inspectPlanDialogVisible = false;
    },

    // 选择质检方案
    handleInspectPlanSelect(plan) {
      if (plan) {
        // 确保planId是数值类型
        let planId = plan.planId;
        if (typeof planId === 'object' && planId !== null) {
          console.warn('方案ID是对象类型，尝试获取其数值表示', planId);
          // 如果是对象，尝试提取其中的ID值
          if (planId.id !== undefined) {
            planId = planId.id;
          } else if (planId.planId !== undefined) {
            planId = planId.planId;
          } else {
            console.error('无法从对象中提取有效ID', planId);
            this.$message.error('方案ID格式不正确');
            return;
          }
        }

        // 转换为数值
        planId = parseInt(planId, 10);
        if (isNaN(planId)) {
          this.$message.error('方案ID必须是数字');
          return;
        }

        // 设置基本字段
        this.form.templateId = planId;
        this.form.templateCode = plan.planCode;
        this.form.templateName = plan.planName;
        // 设置检测方案类型为4
        this.form.qc_types = 4;

        console.log('【手动选择方案】选择的检测方案信息：', {
          ID: planId,
          编码: plan.planCode,
          名称: plan.planName
        });

        // 显示简单成功消息
        this.$message.success(`已选择方案，ID: ${planId}`);

        // 如果有原始数据，可以获取更多信息
        if (plan.originalData) {
          console.log('质检方案原始数据:', plan.originalData);
        }


      }
    },

    // 物料列表基础数据
    initMaterialList() {
      // 初始化物料数据（如果需要）
      this.materialList = this.materialList || [];
      return true;
    },

    // 打开用户选择对话框
    openSelectUserDialog() {
      this.selectUserDialogVisible = true;
    },

    // 用户选择对话框关闭
    closeSelectUserDialog() {
      this.selectUserDialogVisible = false;
    },

    // 用户选择对话框选择用户
    handleUserConfirm(selection) {
      if (selection && selection.length > 0) {
        const selectedUser = selection[0];  // 获取选中的第一个用户
        
        // 确保用户名称不为空
        const userName = selectedUser.nickName || selectedUser.userName || '未命名用户';
        
        // 明确设置inspectorId和inspectorName，使用$set确保响应式更新
        this.$set(this.form, 'inspectorId', userName);
        this.$set(this.form, 'inspectorName', userName);
        
        console.log('选择检测人员:', selectedUser);
        console.log('修改后的检测人员信息:', {
          inspectorId字段存储: this.form.inspectorId,
          inspectorName字段存储: this.form.inspectorName
        });
        
        // 立即验证该字段，更新表单验证状态
        this.$nextTick(() => {
          for (const formRef of ["form", "form2", "form3"]) {
            if (this.$refs[formRef]) {
              this.$refs[formRef].validateField('inspectorId');
            }
          }
        });
      }
    },

    // 表单值变化时重新验证
    checkFormErrors() {
      // 使用setTimeout避免频繁验证
      if (this.validateTimer) {
        clearTimeout(this.validateTimer);
      }

      this.validateTimer = setTimeout(() => {
        // 只有在用户已经交互后才显示验证错误
        this.validateAllForms(this.showValidationErrors);
      }, 500);
    },

    // 在用户首次交互时启用错误显示
    handleUserInteraction() {
      this.isInitialRender = false;
      if (!this.showValidationErrors) {
        // 不要立即设置为true，用户可能只是在浏览
        // this.showValidationErrors = true;
      }
    },

    // 监听表单变化
    setupFormWatchers() {
      // 使用Vue深度监听整个表单对象
      if (!this.formWatcherSetup) {
        this.$watch('form', () => {
          // 用户修改表单时，标记为已交互
          this.handleUserInteraction();
          this.checkFormErrors();
        }, { deep: true });

        // 标记已设置监听
        this.formWatcherSetup = true;
      }
    },

    // 清除所有表单的验证提示
    clearAllValidation() {
      this.showValidationErrors = false;
      const formRefs = ["form", "form2", "form3", "form5", "form7", "form8", "form10", "form11", "form12", "form13", "form14", "form15"];
      formRefs.forEach(formName => {
        if (this.$refs[formName]) {
          try {
            this.$refs[formName].clearValidate();
          } catch (error) {
            console.warn(`清除表单验证失败: ${formName}`, error);
          }
        }
      });

      // 强制重置表单项的错误状态
      this.$nextTick(() => {
        // 移除所有表单项的错误类
        const errorItems = document.querySelectorAll('.el-form-item.is-error');
        errorItems.forEach(item => {
          item.classList.remove('is-error');
        });

        // 重置所有输入框边框颜色
        const inputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner, .el-input-number__inner');
        inputs.forEach(input => {
          input.style.borderColor = '';
        });
      });
    },

    // 打开对话框时初始化
    handleDialogOpen() {
      this.activeTab = 'basic'; // 每次打开时，重置到第一个标签页
      this.isInitialRender = true;
      this.showValidationErrors = false;
      this.formErrorCount = 0;
      this.validateOnSubmit = false;
      
      this.logDebug('对话框打开，初始化表单');
      
      // 重置模板查询状态
      this.resetTemplateQueryStatus();

      // 强制清除所有验证提示
      this.$nextTick(() => {
        this.clearAllValidation();

        // 检查是否需要自动查询检测方案
        if (this.form.goodsCode) {
          this.logDebug("对话框打开时检测到货物编码，准备自动查询检测方案:", this.form.goodsCode);
          this.findTemplateByCode(this.form.goodsCode);
        }

        // 双重保险：添加延迟清理
        setTimeout(() => {
          if (this.isInitialRender) {
            this.clearAllValidation();
            this.isInitialRender = false;
          }
        }, 200);
      });
    },

    // 对话框关闭
    handleClose() {
      this.showValidationErrors = false; // 确保关闭时清除验证状态
      this.clearAllValidation(); // 清除所有验证提示
      this.$emit('cancel');
    },

    // 取消按钮
    cancel() {
      this.showValidationErrors = false; // 确保关闭时清除验证状态
      this.clearAllValidation(); // 清除所有验证提示
      this.resetForm();
      this.$emit("cancel");
    },

    // 表单重置
    resetForm() {
      this.showValidationErrors = false; // 先关闭验证显示
      this.clearAllValidation(); // 清除所有验证提示

      // 等验证规则清除后再重置表单，避免触发验证
      this.$nextTick(() => {
        this.form = {
          iqcId: null,
          iqcCode: null,
          iqcName: null,
          templateId: null,
          sourceDocId: null,
          sourceDocType: 2, // 默认设为2(来料检验单)
          sourceDocCode: null,
          sourceLineId: null,
          supplierId: null,
          supplierCode: null,
          supplierName: null,
          supplierNick: null,
          supplierBatch: null,
          goodsCode: null,
          goodsName: null,
          stockSfn: null,
          unitName: null,
          quantityMinCheckNum: null,
          quantityMaxUnqualifiedNum: null,
          quantityRecivedNum: null,
          quantityCheckNum: null,
          quantityQualifiedNum: null,
          quantityUnqualifiedNum: null,
          crRate: null,
          majRate: null,
          minRate: null,
          crQuantityNum: null,
          majQuantityNum: null,
          minQuantityNum: null,
          checkResult: null,
          reciveDate: null,
          inspectDate: null,
          inspectorId: null,
          status: 2, // 新增模式默认为已提交状态
          remark: null,
          attr1: null,
          attr2: null,
          attr3: null,
          attr4: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          isDelete: null
        };
        this.formErrorCount = 0;
        this.validateOnSubmit = false;
      });
    },

    /** 验证所有表单 */
    validateAllForms(showErrors = true) {
      // 控制是否显示验证错误
      if (showErrors) {
        this.showValidationErrors = true;
      }

      // 同时验证多个表单
      const formRefs = ["form", "form2", "form3", "form5", "form7", "form8", "form10", "form11", "form12", "form13", "form14", "form15"];

      // 记录所有表单是否有效
      let allFormsValid = true;
      let errorCount = 0;

      // 验证计数器，用于判断所有验证是否完成
      let validateCount = 0;

      // 依次验证每个表单
      formRefs.forEach(formName => {
        if (this.$refs[formName]) {
          try {
            this.$refs[formName].validate(valid => {
              validateCount++;

              if (!valid) {
                allFormsValid = false;
                errorCount++;
              }

              // 如果所有表单都已验证完成
              if (validateCount === formRefs.length) {
                // 更新错误计数
                this.formErrorCount = errorCount;
              }
            });
          } catch (error) {
            console.warn(`验证表单失败: ${formName}`, error);
            validateCount++;
          }
        } else {
          validateCount++; // 表单不存在也要增加计数，确保流程继续
        }
      });

      return allFormsValid;
    },

    // 处理接收数量变更
    handleRecivedNumChange() {
      // 如果检测数量大于接收数量，自动调整
      if (this.form.quantityCheckNum > this.form.quantityRecivedNum) {
        this.$message.warning('检测数量已自动调整为接收数量');
        this.form.quantityCheckNum = this.form.quantityRecivedNum;
        // 触发检测数量变更处理
        this.handleQuantityChange();
      }
    },
    
    // 处理数量变更
    handleQuantityChange() {
      // 检查接收数量约束
      if (this.form.quantityRecivedNum && this.form.quantityCheckNum > this.form.quantityRecivedNum) {
        this.$message.warning(`检测数量(${this.form.quantityCheckNum})不能超过接收数量(${this.form.quantityRecivedNum})`);
        this.form.quantityCheckNum = this.form.quantityRecivedNum;
      }
      
      // 更新合格数 - 默认设为等于检测数量(假设全部合格)
      this.form.quantityQualifiedNum = this.form.quantityCheckNum;
      // 不合格数默认为0
      this.form.quantityUnqualifiedNum = 0;
      
      // 重新计算缺陷率
      this.calculateDefectRates();
      
      // 检查是否满足最低检测数量
      if (this.form.quantityMinCheckNum && this.form.quantityCheckNum < this.form.quantityMinCheckNum) {
        this.$message.warning(`检测数量(${this.form.quantityCheckNum})低于规定最低检测数(${this.form.quantityMinCheckNum})`);
      }
    },
    
    // 处理不合格数变化
    handleUnqualifiedNumChange() {
      // 确保合格数与不合格数之和等于检测数量
      if (this.form.quantityCheckNum !== undefined && this.form.quantityUnqualifiedNum !== undefined) {
        // 根据不合格数计算合格数
        this.form.quantityQualifiedNum = this.form.quantityCheckNum - this.form.quantityUnqualifiedNum;
        
        // 检查合格数是否为负数
        if (this.form.quantityQualifiedNum < 0) {
          this.$message.error('不合格数不能大于检测数量');
          this.form.quantityUnqualifiedNum = this.form.quantityCheckNum;
          this.form.quantityQualifiedNum = 0;
        }
        
        // 检查是否超出最大不合格数
        if (this.form.quantityMaxUnqualifiedNum && this.form.quantityUnqualifiedNum > this.form.quantityMaxUnqualifiedNum) {
          this.$message.warning(`不合格数(${this.form.quantityUnqualifiedNum})已超过规定最大值(${this.form.quantityMaxUnqualifiedNum})，检测结果已设为不合格`);
          // 自动设置为不合格
          this.form.checkResult = 2; // 不合格
        }
      }
      // 重置缺陷数量
      this.form.crQuantityNum = 0;
      this.form.majQuantityNum = 0;
      this.form.minQuantityNum = 0;
      this.calculateDefectRates(); // 重新计算缺陷率
    },
    
    // 更新不合格数
    updateUnqualifiedNum() {
      // 根据检测数量和合格数计算不合格数
      if (this.form.quantityCheckNum !== undefined && this.form.quantityQualifiedNum !== undefined) {
        this.form.quantityUnqualifiedNum = this.form.quantityCheckNum - this.form.quantityQualifiedNum;
        
        // 检查不合格数是否为负数
        if (this.form.quantityUnqualifiedNum < 0) {
          this.$message.error('合格数不能大于检测数量');
          this.form.quantityUnqualifiedNum = 0;
          this.form.quantityQualifiedNum = this.form.quantityCheckNum;
        }
      }
    },
    
    // 计算缺陷率
    calculateDefectRates() {
      const checkNum = Number(this.form.quantityCheckNum) || 0;
      if (checkNum <= 0) {
        // 如果检测数量为0或不存在，清空缺陷率
        this.form.crRate = 0;
        this.form.majRate = 0;
        this.form.minRate = 0;
        return;
      }
      
      // 计算各类缺陷率
      const crNum = Number(this.form.crQuantityNum) || 0;
      const majNum = Number(this.form.majQuantityNum) || 0;
      const minNum = Number(this.form.minQuantityNum) || 0;
      
      // 计算百分比，保留两位小数
      this.form.crRate = Number(((crNum / checkNum) * 100).toFixed(2));
      this.form.majRate = Number(((majNum / checkNum) * 100).toFixed(2));
      this.form.minRate = Number(((minNum / checkNum) * 100).toFixed(2));
      
      console.log('缺陷率计算结果:', {
        致命缺陷率: this.form.crRate,
        严重缺陷率: this.form.majRate,
        轻微缺陷率: this.form.minRate
      });
    },

    // 根据货物编码查询对应的质检方案ID
    findTemplateByCode(code) {
      if (!code) {
        this.logDebug('【查询检测方案】编码为空，无法查询');
        return;
      }

      // 记录查询状态
      this.templateQueryStatus.attempted = true;
      this.templateQueryStatus.lastCode = code;
      this.templateQueryStatus.message = "查询中...";

      this.logDebug('【查询检测方案】开始查询，编码：', code);

      // 显示加载提示
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在查询对应的检测方案...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      const findByProductCode = () => {
        this.logDebug('【通过物料编码查询】未找到或查询失败，尝试通过产品编码查询');
        selectQcTemplateProductCode(code)
          .then(productResponse => {
            loadingInstance.close();
            this.logDebug('【通过产品编码查询】查询返回结果：', productResponse);

            if (productResponse && (productResponse.template_id || productResponse.templateId || typeof productResponse === 'number')) {
              this.logDebug('【通过产品编码查询】获取到的检测方案信息：', productResponse);
              this.templateQueryStatus.success = true;
              this.templateQueryStatus.message = "产品编码查询成功";
              this.setTemplateInfo(productResponse);
              this.$message.success(`已通过产品编码查询到检测方案`);
            } else {
              this.logDebug('【查询检测方案】未找到对应的检测方案，请手动选择');
              this.templateQueryStatus.success = false;
              this.templateQueryStatus.message = "未找到对应的检测方案";
              this.$message.info('未找到对应的检测方案，请手动选择');
            }
          })
          .catch(productError => {
            loadingInstance.close();
            this.logDebug('【错误】通过产品编码查询检测方案也失败', productError);
            this.templateQueryStatus.success = false;
            this.templateQueryStatus.message = "所有查询方式均失败";
            this.$message.error('查询检测方案失败，请手动选择：' + (productError.message || "未知错误"));
          });
      };

      // 先尝试通过物料编码查询
      selectQcTemplateProductMaterialCode(code)
        .then(response => {
          this.logDebug('【通过物料编码查询】查询返回结果：', response);
          if (response && (response.template_id || response.templateId || typeof response === 'number')) {
            loadingInstance.close();
            this.logDebug('【通过物料编码查询】获取到的检测方案信息：', response);
            this.templateQueryStatus.success = true;
            this.templateQueryStatus.message = "物料编码查询成功";
            this.setTemplateInfo(response);
            this.$message.success(`已通过物料编码查询到检测方案`);
          } else {
            findByProductCode();
          }
        })
        .catch(error => {
          this.logDebug('【错误】通过物料编码查询检测方案异常', error);
          findByProductCode();
        });
    },

    // 设置模板信息到表单
    setTemplateInfo(templateId) {
      if (!templateId) {
        this.logDebug('【设置模板信息】模板ID为空，无法设置');
        return;
      }

      this.logDebug('【开始设置模板信息】检测方案数据：', templateId);
      
      try {
        // 检查返回值是否为对象，包含更多信息
        if (typeof templateId === 'object' && templateId !== null) {
          // 提取数据字段
          const templateData = templateId;
          const planId = templateData.template_id || templateData.templateId;
          
          if (!planId) {
            this.logDebug('【警告】无法从返回数据中提取模板ID', templateData);
            return;
          }

          // 将模板ID转换为数字
          const numPlanId = parseInt(planId, 10);
          if (isNaN(numPlanId)) {
            this.logDebug('【警告】获取到的检测方案ID格式不正确', planId);
            this.$message.warning('获取到的检测方案ID格式不正确');
            return;
          }

          // 设置基本信息
          this.form.templateId = numPlanId;
          
          // 尝试提取质检要求字段
          if (templateData.quantity_check_num !== undefined) {
            this.form.quantityMinCheckNum = templateData.quantity_check_num;
            this.logDebug('设置最低检测数:', templateData.quantity_check_num);
          }
          if (templateData.quantity_unqualified_num !== undefined) {
            this.form.quantityMaxUnqualifiedNum = templateData.quantity_unqualified_num;
            this.logDebug('设置最大不合格数:', templateData.quantity_unqualified_num);
          }
          if (templateData.cr_rate !== undefined) {
            this.form.crRate = templateData.cr_rate;
            this.logDebug('设置致命缺陷率:', templateData.cr_rate);
          }
          if (templateData.maj_rate !== undefined) {
            this.form.majRate = templateData.maj_rate;
            this.logDebug('设置严重缺陷率:', templateData.maj_rate);
          }
          if (templateData.min_rate !== undefined) {
            this.form.minRate = templateData.min_rate;
            this.logDebug('设置轻微缺陷率:', templateData.min_rate);
          }
          
          // 如果返回了其他字段，也可以设置
          if (templateData.templateCode || templateData.template_code) {
            this.form.templateCode = templateData.templateCode || templateData.template_code;
            this.logDebug('设置模板编码:', this.form.templateCode);
          }
          
          if (templateData.templateName || templateData.template_name) {
            this.form.templateName = templateData.templateName || templateData.template_name;
            this.logDebug('设置模板名称:', this.form.templateName);
          }
          
          this.logDebug('设置的质检规范：', {
            最低检测数: this.form.quantityMinCheckNum,
            最大不合格数: this.form.quantityMaxUnqualifiedNum
          });

        } else {
          // 如果只返回了ID (简单数值)
          // 将模板ID转换为数字
          const numPlanId = parseInt(templateId, 10);
          if (isNaN(numPlanId)) {
            this.logDebug('【警告】获取到的检测方案ID格式不正确', templateId);
            this.$message.warning('获取到的检测方案ID格式不正确');
            return;
          }
          
          // 设置ID
          this.form.templateId = numPlanId;
          this.logDebug('设置模板ID(简单数值):', numPlanId);

          // 设置ID后，模板名称和编码可能为空，此处不再查询详情
          this.$message.success(`已设置检测方案ID: ${numPlanId}`);
        }
      } catch (error) {
        this.logDebug('【错误】设置模板信息时发生异常', error);
        this.$message.error('设置检测方案时发生错误: ' + (error.message || "未知错误"));
      }
    },
    
    // 记录模板状态
    logTemplateStatus() {
      if (this.form.templateId) {
        this.logDebug('当前模板状态:', {
          ID: this.form.templateId,
          编码: this.form.templateCode || '未知',
          名称: this.form.templateName || '未知',
        });
      }
    },

    // 包装来源单据的获取方法，以适配CommonSelector
    fetchSourceDocs(queryParams) {
      return selectCkProductRecptDetectSingle(queryParams).then(res => {
        // 假设API返回的是若依标准格式 { code, msg, rows, total }
        // CommonSelector需要的是一个包含rows和total的对象
        // 如果API直接返回数组，需要做兼容处理
        if (res && res.rows) {
          return {
            rows: res.rows,
            total: res.total
          };
        } else if (Array.isArray(res)) {
          // 如果直接返回数组，则在前端进行分页
          return {
            rows: res,
            total: res.length
          };
        }
        // 如果返回的数据格式不兼容，返回空
        return { rows: [], total: 0 };
      });
    }
  }
};
</script>

<style scoped>
/* 添加自定义样式来隐藏初始验证提示 */
.init-form-status ::v-deep .el-form-item__error {
  display: none !important;
}

/* 当需要显示验证提示时，覆盖上面的样式 */
.show-validation ::v-deep .el-form-item__error {
  display: block !important;
}

/* 添加禁用输入框样式 */
::v-deep .disabled-input .el-input__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #909399;
  cursor: not-allowed;
}

/* 添加样式来消除初始状态下的红色边框 */
.init-form-status ::v-deep .el-form-item.is-error .el-input__inner,
.init-form-status ::v-deep .el-form-item.is-error .el-input__inner:focus,
.init-form-status ::v-deep .el-form-item.is-error .el-textarea__inner,
.init-form-status ::v-deep .el-form-item.is-error .el-textarea__inner:focus,
.init-form-status ::v-deep .el-form-item.is-error .el-input-number__inner,
.init-form-status ::v-deep .el-form-item.is-error .el-input-number__inner:focus {
  border-color: #DCDFE6 !important; /* 使用Element默认边框颜色 */
}

.iqc-dialog >>> .el-dialog {
  margin-top: 2vh !important;
  margin-bottom: 2vh;
  height: 90vh;
  display: flex;
  flex-direction: column;
}

.iqc-dialog >>> .el-dialog__body {
  flex: 1;
  overflow-y: auto;
  padding: 10px 20px;
}

.iqc-dialog >>> .el-tabs__content {
  padding: 20px 0;
}

.iqc-dialog >>> .el-form-item {
  margin-bottom: 18px;
}

.mt5 {
  margin-top: 5px;
}

.index-list-container {
  padding: 10px 0;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #409EFF;
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 8px;
}

/* 添加与过程检验单一致的样式 */
.code-input-wrapper {
  display: flex;
  align-items: center;
}

.select-plan-btn {
  margin-left: 10px;
}

/* 添加表单提示样式 */
.form-tip {
  font-size: 12px;
  color: #67C23A;
  margin-top: 5px;
  line-height: 1.2;
}

.form-tip.warning {
  color: #E6A23C;
}

.form-tip i {
  margin-right: 4px;
}
</style>
